package com.houzehui.mncommodity.config;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.houzehui.mncommodity.entity.Commodity;
import com.houzehui.mncommodity.entity.Commoditypromotion;
import com.houzehui.mncommodity.service.ICommodityService;
import com.houzehui.mncommodity.service.ICommoditypromotionService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.listener.AcknowledgingMessageListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class kafkacomnumer implements AcknowledgingMessageListener<String,String> {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ICommodityService iCommodityService;

    @Autowired
    ICommoditypromotionService iCommoditypromotionService;

    @KafkaListener(groupId = "test-group",topics = {"test"})
    @Override
    public void onMessage(ConsumerRecord<String, String> data, Acknowledgment acknowledgment) {


        String key = data.key();
        Commodity commodity = JSON.parseObject(data.value(), Commodity.class);

        Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, null, 10, TimeUnit.SECONDS);
        if(!lock){
            return;
        }
        commodity.setDatetimes(new Date());
        //调用二维码服务
        String uuid = UUID.randomUUID().toString();
        String boby = HttpRequest.get("http://localhost:89/qrcode/getqrcode")
                .header("token", uuid)
                .form("name",commodity.getName())

                .form("price",commodity.getPrice())
                .execute().body();
        //解析json对象
        MsgResult msgResult = JSON.parseObject(boby, MsgResult.class);

        Object msgData = msgResult.getMsgData();

        //赋值实体类
        commodity.setQrcode(msgData.toString());
        //redis同步数据

        redisTemplate.opsForValue().setIfAbsent("commodity"+commodity.getId(),commodity);
//        //增加
//        iCommodityService.save(commodity);
//
//
//        List<Integer> proidss = commodity.getProidss();
//        System.err.println(proidss);
//        for (Integer integer : proidss) {
//            Commoditypromotion commoditypromotion = new Commoditypromotion().setCid(commodity.getId()).setPid(integer);
//            System.err.println(commoditypromotion);
//           iCommoditypromotionService.save(commoditypromotion);
//        }

        iCommodityService.add(commodity);





        acknowledgment.acknowledge();
    }
}
